﻿using EShop.Net.Configuration;
using EShop.Net.Model.Entity;
using EShop.Net.Util.Date;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Configuration.Json;
using Microsoft.IdentityModel.Tokens;
using System;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;

namespace EShop.Net.Auth
{
    /// <summary>
    /// JWTToken生成类
    /// </summary>
    public class JwtToken<T>
    {
        /// <summary>
        /// 配置属性
        /// </summary>
        private static IConfiguration configuration;

        public static IConfiguration Configuration { get => configuration; set => configuration = value; }

        /// <summary>
        /// 生成Token
        /// </summary>
        /// <param name="claims"></param>
        /// <param name="contentPath"></param>
        /// <param name="userType">用户类型【0-admin，1-user】</param>
        /// <returns></returns>
        public static TokenObj<T> GetJwtToken(Claim[] claims, string contentPath, int userType)
        {
            string Path = "appsettings.json";
            Configuration = new ConfigurationBuilder().SetBasePath(contentPath).Add(new JsonConfigurationSource { Path = Path, Optional = false, ReloadOnChange = true }).Build();

            SymmetricSecurityKey key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(AppSettingsConstVars.JwtConfigSecretKey));
            DateTime expires;
            if (userType == 0)
            {
                expires = DateTime.Now.AddMinutes(Convert.ToDouble(AppSettingsConstVars.JwtConfigAdminExpires));
            }
            else
            {
                expires = DateTime.Now.AddMinutes(Convert.ToDouble(AppSettingsConstVars.JwtConfigUserExpires));
            }
            SigningCredentials creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
            JwtSecurityToken token = new JwtSecurityToken(
                issuer: AppSettingsConstVars.JwtConfigIssuer,
                audience: AppSettingsConstVars.JwtConfigAudience,
                claims: claims,
                notBefore: DateTime.Now,
                expires: expires,
                signingCredentials: creds
            );
            string jwtToken = new JwtSecurityTokenHandler().WriteToken(token);  // 生成Token
            TokenObj<T> tokenObj = new TokenObj<T>();
            if (string.IsNullOrEmpty(jwtToken))
            {
                tokenObj.token = "Token获取失败";
                tokenObj.expires = 0;
            }
            else
            {
                tokenObj.token = jwtToken;
                tokenObj.expires = DateTimeHelper.BeijingTimeToUnixTimeStamp13(expires);
            }
            return tokenObj;
        }
    }
}
